<template>
  <div class="patients-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="我的患者"
      left-arrow
      @click-left="onClickLeft"
      fixed
    >
      <template #right>
        <van-icon name="setting-o" size="18" @click="onClickRight" />
      </template>
    </van-nav-bar>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchForm.patientName"
        placeholder="输入患者姓名搜索"
        shape="round"
        show-action
        @search="onSearch"
      >
        <template #action>
          <div @click="showFilter = true">筛选</div>
        </template>
      </van-search>
    </div>
    
    <!-- 患者列表 -->
    <div class="patient-list-container">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <!-- 骨架屏 -->
          <template v-if="loading && patientList.length === 0">
            <div class="patient-item skeleton" v-for="i in 3" :key="i">
              <div class="patient-avatar skeleton-avatar"></div>
              <div class="patient-info skeleton-info">
                <div class="skeleton-line skeleton-title"></div>
                <div class="skeleton-line"></div>
                <div class="skeleton-line"></div>
                <div class="skeleton-line"></div>
              </div>
            </div>
          </template>

          <div class="patient-item" v-for="patient in patientList" :key="patient.visitId" @click="goToPatientDetail(patient)">
            <div class="patient-avatar">
              <img :src="getAvatarByGender(patient.gender)" alt="头像">
            </div>
            <div class="patient-info">
              <div class="patient-name">
                {{ patient.patientName }}
                <span class="patient-gender">{{ patient.gender === 1 ? '男' : '女' }}</span>
                <span class="patient-age">{{ calculateAge(patient) }}岁</span>
              </div>
              <div class="patient-diagnosis">诊断: {{ patient.diagnosisName || '暂无' }}</div>
              <div class="patient-department">科室: {{ patient.departmentName }}</div>
              <div class="patient-visit-time">就诊时间: {{ formatDate(patient.visitTime) }}</div>
            </div>
            <van-icon name="arrow" class="arrow-icon" />
          </div>

          <!-- 空状态 -->
          <van-empty 
            v-if="!loading && patientList.length === 0" 
            description="暂无患者数据" 
          />
        </van-list>
      </van-pull-refresh>
    </div>
    
    <!-- 筛选弹出层 -->
    <van-popup 
      v-model:show="showFilter" 
      position="right" 
      overlay
      teleport="body"
      class="filter-popup"
    >
      <div class="filter-container">
        <van-nav-bar
          title="筛选条件"
          left-arrow
          @click-left="showFilter = false"
        />
        
        <van-form @submit="onFilterSubmit">
          <van-cell-group inset>
            <van-field
              v-model="searchForm.departmentName"
              label="科室"
              placeholder="请输入科室名称"
            />
            
            <van-field
              v-model="searchForm.visitNo"
              label="就诊号"
              placeholder="请输入就诊号"
            />
            
            <van-field
              v-model="searchForm.idCard"
              label="身份证号"
              placeholder="请输入身份证号"
            />
          </van-cell-group>
          
          <div class="filter-buttons">
            <van-button round block type="primary" native-type="submit">
              确认筛选
            </van-button>
            
            <van-button round block type="default" class="reset-button" @click="resetFilter">
              重置筛选
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showConfirmDialog } from 'vant';
import { getPatientsView } from '@/api/patient';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 患者列表数据
const patientList = ref([]);
const loading = ref(false);
const refreshing = ref(false);
const finished = ref(false);
const showFilter = ref(false);
const pageNum = ref(1);
const pageSize = ref(10);

// 搜索表单
const searchForm = reactive({
  userId: userStore.userId || '',
  roleId: userStore.userRole || '',
  patientName: '',
  departmentName: '',
  visitNo: '',
  idCard: ''
});

// 获取患者列表
const fetchPatients = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pageNum.value = 1;
      patientList.value = [];
    }
    
    loading.value = true;
    
    const params = {
      ...searchForm,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    };
    
    const res = await getPatientsView(params);
    
    if (res.rows && res.rows.length) {
      if (isRefresh) {
        patientList.value = res.rows;
      } else {
        patientList.value = [...patientList.value, ...res.rows];
      }
      
      pageNum.value++;
      // 判断是否已加载完所有数据
      if (patientList.value.length >= res.total) {
        finished.value = true;
      }
    } else {
      finished.value = true;
    }
  } catch (error) {
    console.error('获取患者列表失败', error);
    showToast('获取患者列表失败');
    finished.value = true; // 确保出错时也设置完成状态
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 下拉刷新
const onRefresh = () => {
  finished.value = false;
  fetchPatients(true);
};

// 上拉加载
const onLoad = () => {
  if (!loading.value) {
    fetchPatients();
  }
};

// 搜索
const onSearch = () => {
  finished.value = false;
  fetchPatients(true);
};

// 筛选提交
const onFilterSubmit = () => {
  showFilter.value = false;
  finished.value = false;
  fetchPatients(true);
};

// 重置筛选
const resetFilter = () => {
  searchForm.departmentName = '';
  searchForm.visitNo = '';
  searchForm.idCard = '';
};

// 根据性别获取头像
const getAvatarByGender = (gender) => {
  return gender === 1 
    ? 'https://img01.yzcdn.cn/vant/cat.jpeg' 
    : 'https://img01.yzcdn.cn/vant/dog.jpeg';
};

// 计算年龄
const calculateAge = (patient) => {
  // 简单实现，实际应该根据身份证或出生日期计算
  return patient.age || Math.floor(Math.random() * 60 + 20);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (e) {
    return dateStr;
  }
};

// 跳转到患者详情
const goToPatientDetail = (patient) => {
  router.push(`/patient/${patient.patientId}/${patient.visitId}`);
};

// 顶部导航栏左侧按钮点击事件
const onClickLeft = () => {
  showConfirmDialog({
    title: '提示',
    message: '确定要退出登录吗？',
  }).then(() => {
    userStore.logout();
    router.replace('/login');
  }).catch(() => {
    // 取消操作
  });
};

// 顶部导航栏右侧按钮点击事件
const onClickRight = () => {
  showToast('功能开发中');
};

// 页面加载时获取患者列表
onMounted(() => {
  fetchPatients();
});
</script>

<style scoped>
.patients-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--background-color);
}

.search-bar {
  position: sticky;
  top: 46px;
  z-index: 100;
  margin-top: 46px;
}

.patient-list-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 50px;
}

.patient-item {
  background-color: #fff;
  margin: 8px;
  padding: 12px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
}

.patient-avatar {
  width: 50px;
  height: 50px;
  margin-right: 12px;
  border-radius: 50%;
  overflow: hidden;
}

.patient-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.patient-info {
  flex: 1;
}

.patient-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.patient-gender, .patient-age {
  font-size: 14px;
  color: #666;
  margin-left: 8px;
  font-weight: normal;
}

.patient-diagnosis, .patient-department, .patient-visit-time {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.arrow-icon {
  color: #999;
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
}

.filter-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 骨架屏样式 */
.skeleton {
  background-color: #fff;
}

.skeleton-avatar {
  width: 50px;
  height: 50px;
  background-color: #f2f3f5;
  border-radius: 50%;
}

.skeleton-info {
  flex: 1;
}

.skeleton-line {
  height: 16px;
  margin-bottom: 8px;
  background-color: #f2f3f5;
  border-radius: 2px;
}

.skeleton-title {
  width: 40%;
  height: 20px;
}

.skeleton-line:nth-child(2) {
  width: 60%;
}

.skeleton-line:nth-child(3) {
  width: 50%;
}

.skeleton-line:nth-child(4) {
  width: 80%;
  margin-bottom: 0;
}

.filter-popup {
  width: 80%;
  height: 100%;
}

.filter-buttons {
  margin: 16px;
}

.reset-button {
  margin-top: 10px;
}
</style> 